﻿using Ljy_VoteSys.Models.Database;
using Ljy_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ljy_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FindCompanyController : Controller
    {
        //注入jwt服务
        private readonly IJWTService _jwtService;
        //定义数据库上下文
        private readonly Ljy_VoteSysContext _db;
        public string User => Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;

        public FindCompanyController(IJWTService jwtService, Ljy_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        /// <summary>
        /// 根据公司名/id查找....
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[Authorize]
        public List<Ticket> FindCompany(string Company, int Classid,int PageNo)
        {
            var data = _db.Tickets.Where(x => x.CompanyName.Contains(Company)|| x.Classid == Classid)
                .Skip((PageNo- 1) * 10)//一次最多返回10
                .Take(10)
                .ToList();
            if (data == null) return null;
            return data;
        }
        /// <summary>
        /// 根据公司名和classid投票 完结撒花....
        /// </summary>
        /// <returns></returns>

        [HttpPut]
        [Authorize]
        public string GetTicket(int ClassId,string Company)
        {
            var check = _db.UserTables.FirstOrDefault(x => x.Username == User);
            if (check == null)
                return " 您不是普通用户,请重新登录";
            var data = _db.Tickets.FirstOrDefault(x => x.Classid == ClassId && x.CompanyName==Company);
            if (data == null)
                return "找不到此作品,请重新输入";
            if (check.TicketOneday > 0)
            {
                data.TotalTicket = data.TotalTicket + 1;
                check.TicketOneday = check.TicketOneday - 1;
                var row = _db.SaveChanges();
                if (row > 0)
                    return "用户投票成功,你当前还可以投" + check.TicketOneday + "票";
            }
            return "您今日投票次数已用完,请明天再投票";

        }
    }
}
